package com.aimosheng.common.utils;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.aimosheng.common.CommonAppConfig;
import com.aimosheng.common.CommonAppContext;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;

/**
 * Created by cxf on 2018/6/22.
 */

public class BitmapUtil {

    private static BitmapUtil sInstance;
    private Resources mResources;
    private BitmapFactory.Options mOptions;

    private BitmapUtil() {
        mResources = CommonAppContext.sInstance.getResources();
        mOptions = new BitmapFactory.Options();
        mOptions.inPreferredConfig = Bitmap.Config.RGB_565;
        mOptions.inDither = true;
        mOptions.inSampleSize = 1;
    }

    public static BitmapUtil getInstance() {
        if (sInstance == null) {
            synchronized (BitmapUtil.class) {
                if (sInstance == null) {
                    sInstance = new BitmapUtil();
                }
            }
        }
        return sInstance;
    }


    public Bitmap decodeBitmap(int imgRes) {
        Bitmap bitmap = null;
        try {
            byte[] bytes = IOUtils.toByteArray(mResources.openRawResource(imgRes));
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, mOptions);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new SoftReference<>(bitmap).get();
    }

    // 5. Drawable----> Bitmap
    public static Bitmap DrawableToBitmap(Drawable drawable) {
        // 获取 drawable 长宽
        int width = drawable.getIntrinsicWidth();
        int heigh = drawable.getIntrinsicHeight();
        drawable.setBounds(0, 0, width, heigh);
        // 获取drawable的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 创建bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, heigh, config);
        // 创建bitmap画布
        Canvas canvas = new Canvas(bitmap);
        // 将drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 把Bitmap保存成图片文件
     *
     * @param bitmap
     */
    public String saveBitmap(Context context, Bitmap bitmap) {
        String path = null;
        File dir = new File(CommonAppConfig.CAMERA_IMAGE_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File imageFile = new File(dir, DateFormatUtil.getCurTimeString() + ".jpg");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            path = imageFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(), path, imageFile.getName(), null);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(new File(path));
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return path;
    }


    //文件保存到相册
    public boolean savePhotoFile(Context context, String fromPath) {
        File fromFile = new File(fromPath);
        if (!fromFile.exists()) {
            System.out.println("源文件不存在");
            return false;
        }
        if (!fromFile.isFile()) {
            System.out.println("源文件不是文件");
            return false;
        }
        try {
            //方法一
            //复制文件到指定目录下
            String toPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM/Camera/";
            File toFile = new File(toPath);
            if (!toFile.exists()) {
                toFile.mkdir();//没有该目录，创建一个
            }
            FileInputStream fromStream = new FileInputStream(fromPath);    //读入原文件
            FileOutputStream toStream = new FileOutputStream(toPath + fromFile.getName());
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fromStream.read(buffer)) > 0) {
                toStream.write(buffer, 0, len);
            }
            fromStream.close();
            toStream.flush();
            toStream.close();
            //刷新相册
            MediaStore.Images.Media.insertImage(context.getContentResolver(), fromFile.getAbsolutePath(), fromFile.getName(), null);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(new File(toPath));
            intent.setData(uri);
            context.sendBroadcast(intent);
            return true;
            //方法二
            //获得源文件路径，直接把插入到系统图库，可能并不是DCIM目录下
        /*Context context = AppActivity.getContext();
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    fromFile.getAbsolutePath(), fromFile.getName(), null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(fromFile.getParent()))));*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
